package servlet;

import service.Userservice;
import vo.ResultInfo;
import vo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;


@WebServlet("/Userservlet")
public class Userservlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
        String name=request.getParameter("username");
        String pwd=request.getParameter("password");
        Userservice userservice =new Userservice();
        ResultInfo<User> resultInfo = null;
        try {
            resultInfo = userservice.login(name,pwd);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

        String imageText = request.getParameter("image");
        // 图片的验证码
        String text = (String) request.getSession().getAttribute("text");

        if (!text.equalsIgnoreCase(imageText)) {
            request.setAttribute("imageMess", "验证码输入错误!");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }

        if(resultInfo.getCode()==0){
           request.setAttribute("error_which", resultInfo.getWhich());
           request.getRequestDispatcher("login.jsp").forward(request,response);
       }
       else {
           HttpSession session=request.getSession();
           session.setAttribute("user", resultInfo.getResult());
           request.getRequestDispatcher("/chatroom.jsp").forward(request,response);
       }

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
              doPost(request, response);
    }
}
